const cheerio = require('cheerio');
const _ = require('underscore');
const Base = require('./_base')
const path = window.require('path');
const md5 = require('js-md5');

export default class Gather extends Base{
	constructor(reportCb) {
	    super(reportCb);
	    this.enterurl = 'http://www.baxter.it/en/products'
	    this.host='http://www.baxter.it';
      this.pathname = path.resolve('data/' + md5(this.enterurl))
	  }
	  getProductUrls = async() => {
	  	let res = await fetch(this.enterurl).then(res => res.text());
	  	 let $ = cheerio.load(res)
	  	 let urls=[];
	  	 let html=$('#tblMulti2').html();
	  	 if($("tr",html).length<1 || $("tr",html)===undefined)return false;
	  	 $("tr",html).each(function(i,e){
	  	 	if($('td',$(this).html())==undefined || $('td',$(this).html()).length<1)return false;
	  	 	$('td',$(this).html()).each(function(j,el){
	  	 		if($('a',$(this).html())==undefined || $('a',$(this).html()).length<1)return false;
	  	 		urls.push($('a',$(this).html()).eq(0).attr('href'));
	  	 	});
	  	 });
	  	 let rurls=[];
	  	 for(var i of _.range(urls.slice(0,4).length)){
	  	 	let url = urls[i]
	  	 	this.status.msg = '获取列表'
	  	 	this.status.current = i + 1
	  	 	this.status.count = urls.length
	  	 	this.reportCb(this.status)
	  	 	let res=await fetch(this.host+url).then(res => res.text());
	  	 	let $ = cheerio.load(res)
	  	 	// 获取商品的详细地址
	  	 	let goods_path_list=[];
	  	 	let html=$('#tblMulti2').html();
	  	 	if($("tr",html).length<1 || $("tr",html)===undefined)return false;
	  	 	$("tr",html).each(function(i,e){
	  	 		if($('td',$(this).html())==undefined || $('td',$(this).html()).length<1)return false;
	  	 		$('td',$(this).html()).each(function(j,el){
	  	 			if($('a',$(this).html())==undefined || $('a',$(this).html()).length<1)return false;
	  	 			if($('a',$(this).html()).eq(0).attr('href').indexOf('http://www.baxter.it')>=0){
	  	 			rurls.push($('a',$(this).html()).eq(0).attr('href'));
	  	 			}
	  	 		});
	  	 	});
	  	 }
	  	 return rurls
	  }
	  getProduct = async(url) => {
	  	let res = await fetch(url).then(res => res.text());
	  	let $ = cheerio.load(res)
	  	// 获取商品的详细地址
	  	var product={};
	  	let goods_imgs=$('script').eq(-3).html();
	  	goods_imgs=goods_imgs.substring(goods_imgs.indexOf('[{'),goods_imgs.indexOf('}]')+2);
	  	goods_imgs=eval(goods_imgs);
	  	product.brand_num='baxter';
	  	// product.origin_html=$('html').html();
	  	product.origin_url =url;
	  	product.name=goods_imgs[0].description.split('|')[0];
	  	let description='<div>'+goods_imgs[0].description+'</div>';
	  	product.description=$('div',description).text();
	  	product.date=new Date().getTime();
	  	product.images=[];
	  	product.path=[];
	  	product.local_path=[];
	  	for(let key2 of goods_imgs){
	  		let img=key2.image;
	  		product.images.push({"pic_url":img});
	  	}
	  	return product
	  }
}
